﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.ActivateCardNextActivity.MyPopListViewClick;
import com.kuanter.kuanterauto.activity.ActivateCardNextActivity.SelecterGradePopupWindow;
import com.kuanter.kuanterauto.activity.ActivateCardNextActivity.SelecterGradePopupWindow.PopInsuranceAdapter;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.Utility;
import com.umeng.analytics.MobclickAgent;
/**
 * 个人信息
 * @author lenovo
 *
 */
public class PersonalInfoActivity extends WuyangBaseActivity {

	private static final int PLEASE_AUTOCODE_PHONE = 0;
	private static final int PLEASE_AUTOCODE_EMAIL = 1;
	private Intent intent = new Intent();
	private Button personal_info_header_left_btn;
	private View modify_phone_number_goto;
	private View modify_email_goto;
	private View modify_password_goto;
	private String userId;
	private String userEmail;
	private String mobileNumber;
	private String userRealName;
	private TextView userRealName_tv;
	private TextView mobileNumber_tv;
	private TextView userEmail_tv;
	private TextView userAddress_tv;
	private String address;
	private ArrayList<String> sexs = new ArrayList<String>();
	private SelecterGradePopupWindow menuWindow;
	private TextView optionSex;
	
	private JSONObject jsonObjectResult;
	/**
	 * 修改用户性别请求响应
	 */
	Handler handler_UPDATE_SEX = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
								jsonObjectResult = JSON.parseObject(result);
								SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
								SharedPreferences.Editor editor = sp.edit();
								editor.putString("sex", optionSex.getText().toString());
								editor.commit();
								showToast("修改成功");
								finishProgress();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							jsonObjectResult = JSON.parseObject(result);
							showToast(jsonObjectResult.getString("errorMsg"));
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("异常");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private String sex;
	/*@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		this.setBodyControlViewText();
		super.onResume();
	}*/
	public void onResume() {
	    super.onResume();
	    setBodyControlViewText();
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_info);
		this.initBodyControlView();
		this.registerListener();
		this.setBodyControlViewText();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(null != data){
			switch (requestCode) {
			case PersonalInfoActivity.PLEASE_AUTOCODE_PHONE:
				mobileNumber_tv.setText(data.getStringExtra("phone_nubmer"));
				SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
				Editor editor = sp.edit();
				editor.putString("mobileNumber", data.getStringExtra("phone_nubmer"));
				editor.commit();
				this.setBodyControlViewText();
				break;

			case PersonalInfoActivity.PLEASE_AUTOCODE_EMAIL:
				userEmail_tv.setText(data.getStringExtra("email"));
				SharedPreferences sp1 = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
				Editor editor1 = sp1.edit();
				editor1.putString("userEmail", data.getStringExtra("email"));
				editor1.commit();
				this.setBodyControlViewText();
				break;
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	//optionSex
	public void optionSex(View v){
		menuWindow.showAtLocation(this.findViewById(R.id.temp9), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.personal_info_header_left_btn:
			this.finish();
			break;
		case R.id.modify_phone_number_goto:
			intent.setClass(this, PersonalInfoPhoneNumberSettingActivity.class);
			startActivityForResult(intent, PersonalInfoActivity.PLEASE_AUTOCODE_PHONE) ;
			break;
		case R.id.modify_email_goto:
			intent.setClass(this, PersonalInfoEmailSettingActivity.class);
			startActivityForResult(intent, PersonalInfoActivity.PLEASE_AUTOCODE_EMAIL) ;
			break;
		case R.id.modify_password_goto:
			intent.setClass(this, PersonalInfoPasswordSettingActivity.class);
			startActivity(intent) ;
			break;
		default:
			break;
		}
	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		personal_info_header_left_btn = (Button)this.findViewById(R.id.personal_info_header_left_btn);
		modify_phone_number_goto = this.findViewById(R.id.modify_phone_number_goto);
		modify_email_goto = this.findViewById(R.id.modify_email_goto);
		modify_password_goto = this.findViewById(R.id.modify_password_goto);
		//用户名
		userRealName_tv = (TextView)this.findViewById(R.id.userRealName_tv);
		sexs .add("男");
		sexs.add("女");
		menuWindow = new SelecterGradePopupWindow(this, new MyPopListViewClick(),sexs);
		optionSex = (TextView)findViewById(R.id.optionSex);
		//手机号码
		mobileNumber_tv = (TextView)this.findViewById(R.id.mobileNumber_tv);
		//email
		userEmail_tv = (TextView)this.findViewById(R.id.userEmail_tv);
		//user address
		userAddress_tv = (TextView)this.findViewById(R.id.userAddress_tv);
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		personal_info_header_left_btn.setOnClickListener(this);
		modify_phone_number_goto.setOnClickListener(this);
		modify_email_goto.setOnClickListener(this);
		modify_password_goto.setOnClickListener(this);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		
		SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
		userId = sp.getString("id", "");
		mobileNumber = sp.getString("mobileNumber", "");
		userEmail = sp.getString("userEmail", "");
		userRealName = sp.getString("userRealName", "");
		sex = sp.getString("sex", "");
		address = sp.getString("address", "");
		//给控件附个人信息值
		userRealName_tv.setText(userRealName);
		mobileNumber_tv.setText(mobileNumber.substring(0, 3)+"****"+mobileNumber.substring(8));
		if(!userEmail.equals("")){
			userEmail_tv.setText("****"+userEmail.substring(userEmail.indexOf("@")-2));
		}else {
			userEmail_tv.setText("");
		}
		if(null != sex&&!"".equals(sex)){
			optionSex.setText(sex);
		}else{
			optionSex.setText("请选择");
		}
		if(null != address&&!"".equals(address)){
			userAddress_tv.setText(address);
		}else{
			userAddress_tv.setText("暂无");
		}
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		
	}
	public class MyPopListViewClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
				//0空1男2女
				String sex = sexs.get(position);
				optionSex.setText(sex);
				String sexNo = "0";
				if("女".equals(sex)){
					sexNo = "2";
				}else if("男".equals(sex)){
					sexNo = "1";
				}else 
					sexNo = "0";
				
				menuWindow.dismiss();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
//				params.add(new BasicNameValuePair("mobileNumber", null));
				params.add(new BasicNameValuePair("userId", userId + ""));
//				params.add(new BasicNameValuePair("email", null));
				params.add(new BasicNameValuePair("gender", sexNo));
				new DataLoader(PersonalInfoActivity.this).DisplayData(MainConstants.HOST_test+HttpConfigAPI.UPDATE_SEX, params, handler_UPDATE_SEX, "", false);
		}

	}
	public class SelecterGradePopupWindow extends PopupWindow {


		private TextView btn_cancel;
		private View mMenuView;
		
		ListView insuranceview;
		LayoutInflater inflater;
		
		PopInsuranceAdapter adapter;
		
		List<String> ci_pop;

		public SelecterGradePopupWindow(Activity context,OnItemClickListener itemsOnClick,List<String> ci_pop) {
			super(context);
			this.ci_pop = ci_pop;
			
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mMenuView = inflater.inflate(R.layout.alert_dialog, null);
			btn_cancel = (TextView) mMenuView.findViewById(R.id.btn_cancel);
			//取消按钮
			btn_cancel.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					//销毁弹出框
					dismiss();
				}
			});
			
			insuranceview = (ListView) mMenuView.findViewById(R.id.insuranceview);
			insuranceview.setOnItemClickListener(itemsOnClick);
			
			adapter = new PopInsuranceAdapter();
			insuranceview.setAdapter(adapter);
			Utility.setListViewHeightBasedOnChildren(insuranceview);
			
			//设置SelectPicPopupWindow的View
			this.setContentView(mMenuView);
			//设置SelectPicPopupWindow弹出窗体的宽
			this.setWidth(LayoutParams.FILL_PARENT);
			//设置SelectPicPopupWindow弹出窗体的高
			this.setHeight(LayoutParams.WRAP_CONTENT);
			//设置SelectPicPopupWindow弹出窗体可点击
			this.setFocusable(true);
			//设置SelectPicPopupWindow弹出窗体动画效果
			this.setAnimationStyle(R.style.AnimBottom);
			//实例化一个ColorDrawable颜色为半透明
			ColorDrawable dw = new ColorDrawable(0xb0000000);
			//设置SelectPicPopupWindow弹出窗体的背景
			this.setBackgroundDrawable(dw);
			//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
			mMenuView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					
					int height = mMenuView.findViewById(R.id.pop_layout).getTop();
					int y=(int) event.getY();
					if(event.getAction()==MotionEvent.ACTION_UP){
						if(y<height){
							dismiss();
						}
					}				
					return true;
				}
			});

		}
		
		class PopInsuranceAdapter extends BaseAdapter {
			@Override
			public int getCount() {
				return ci_pop == null ? 0 : ci_pop.size();
			}

			@Override
			public Object getItem(int arg0) {
				return ci_pop.get(arg0);
			}

			@Override
			public long getItemId(int arg0) {
				return arg0;
			}

			@Override
			public View getView(int position, View view, ViewGroup parent) {
				if(view == null) {
					view = inflater.inflate(R.layout.pop_insurance_item, null);
				}
				TextView item_insurance = (TextView) view.findViewById(R.id.item_insurance);
				item_insurance.setText(ci_pop.get(position));
				return view;
			}
			
		}

	}
	
}
